<script setup lang="ts">
import RoomStatus from './components/RoomStatus .vue'
import RoomMessage from './components/RoomMessage.vue'
import RoomAction from './components/RoomAction.vue'
import { io } from 'socket.io-client'
import type { Socket } from 'socket.io-client'
import { onMounted } from 'vue'
import { onUnmounted } from 'vue'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import { MsgType, OrderType } from '@/enums'
import type { Message, TimeMessages } from '@/types/room'
import { ref } from 'vue'
import { getConsultOrderDetail } from '@/services/consult'
import { nextTick } from 'vue'
import type { Image } from '@/types/consult'
import dayjs from 'dayjs'
import { provide } from 'vue'
import { showToast } from 'vant'
const completeEva = (score: number) => {
  const item = list.value.find((item) => item.msgType === MsgType.CardEvaForm)
  if (item) {
    item.msg.evaluateDoc = { score }
    item.msgType = MsgType.CardEva
  }
}
provide('completeEva', completeEva)

const list = ref<Message[]>([])
const consult = ref()
const getOrderDetail = async () => {
  const res = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = res.data
}
const route = useRoute()
let socket: Socket
const userStore = useUserStore()

// ...
provide('consult', consult)

onMounted(() => {
  socket = io(baseURL, {
    auth: {
      token: 'Bearer ' + userStore.user?.token
    },
    query: {
      orderId: route.query.orderId
    }
  })
  socket.on('connect', () => {
    // 建立连接成功
    console.log('connect')
    list.value = []
  })

  socket.on('error', (event) => {
    // 错误异常消息
    console.log('error', event)
  })

  socket.on('disconnect', () => {
    // 已经断开连接
    console.log('disconnect')
  })
  // 聊天记录
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    if (!data.length) {
      return showToast('没有聊天记录了')
    }
    const arr: Message[] = []
    data.forEach((item, i) => {
      if (i === 0) time.value = item.createTime
      arr.push({
        msgType: MsgType.Notify,
        msg: { content: item.createTime },
        createTime: item.createTime,
        id: item.createTime
      })
      arr.push(...item.items)
    })
    list.value.unshift(...arr)
    // loading.value = false
    initialMsg.value = true
    nextTick(() => {
      socket.emit('updateMsgStatus', arr[arr.length - 1].id)
      window.scrollTo(0, document.body.scrollHeight)
      initialMsg.value = false
    })
  })
  //监听订单状态
  socket.on('statusChange', () => {
    getOrderDetail()
  })
  // 接收消息 在onMounted注册
  socket.on('receiveChatMsg', async (event) => {
    list.value.push(event)
    await nextTick()
    socket.emit('updateMsgStatus', event.id)
    if (event.msgType === MsgType.MsgText) window.scrollTo(0, document.body.scrollHeight)
    else window.scrollTo(0, document.body.scrollHeight + 50)
  })
  getOrderDetail()
})
onUnmounted(() => {
  socket.close()
})
const initialMsg = ref(true)

const handleSendText = (text: string) => {
  socket.emit('sendChatMsg', {
    from: userStore.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: { content: text }
  })
}
const handleSendImage = (img: Image) => {
  socket.emit('sendChatMsg', {
    from: useUserStore().user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: { picture: img }
  })
}
const loading = ref(false)
const onRefresh = async () => {
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
  loading.value = false
}
const time = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="医生问诊室" />
    <room-status :status="consult?.status" :countdown="consult?.countdown" />
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-message :list="list" />
    </van-pull-refresh>

    <room-action
      :disabled="consult?.status !== OrderType.ConsultChat"
      @send-text="handleSendText"
      @send-image="handleSendImage"
    />
  </div>
</template>
